const {app, BrowserWindow, dialog, ipcMain} = require('electron')
const {user} = require('./core/db')
const {join} = require('path')
const fs = require("fs");
const ExcelJS = require('exceljs');

// 屏蔽安全警告
// ectron Security Warning (Insecure Content-Security-Policy)
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'

const readExcel = (file) => {
    return new Promise((resolve, reject) => {
        const fileReader = new FileReader();
        fileReader.readAsArrayBuffer(file);

        fileReader.onload = (e) => {
            const bufferArray = e.target.result;
            const wb = XLSX.read(bufferArray, {type: "buffer"});
            const wsname = wb.SheetNames[0];
            const ws = wb.Sheets[wsname];
            const data = XLSX.utils.sheet_to_json(ws, {
                raw: true,
                header: ['source', 'target']
            });

            resolve(data);
        };
        fileReader.onerror = (error) => {
            reject(error);
        };
    });
};

// 创建浏览器窗口时，调用这个函数
const createWindow = () => {
    const win = new BrowserWindow({
        title: '医师电子化注册信息系统（机构版）',//如果index.html没有title标签会使用该字段内容做为软件名称
        icon: join(__dirname, '../public/favicon.ico'), // 软件图标
        width: 1600,
        height: 1000,
        // maxWidth: 1920,
        // minHeight: 1080,
        show: false, // 窗口创建时隐藏
        resizable: false, // 窗口大小是否可调整，false就是不可以调整
        //frame: false, // 去除顶部标题以及菜单栏
        webPreferences: {
            preload: join(__dirname, 'preload.js'),
            nodeIntegration: true,
            contextIsolation: true // 注意：在Electron 12+版本中，需要设置contextIsolation为false才能使用nodeIntegration
        }
    })
    //win.maximize()   // 最大化窗口

    // 设置菜单为空，完全隐藏菜单栏
    win.setMenu(null);

    // win.loadURL('http://localhost:3000')

    // development模式
    if (process.env.VITE_DEV_SERVER_URL) {
        win.loadURL(process.env.VITE_DEV_SERVER_URL)
        // 开启调试台 F12
        win.webContents.openDevTools()
    } else {
        win.loadFile(join(__dirname, '../dist/index.html'))
    }
    win.webContents.openDevTools()

    // 程序启动时 会出现短暂的白屏 所以窗口初始化完成后展示
    win.once('ready-to-show', () => {
        win.show(); // 窗口初始化完成后展示
    });

    // 监听来自渲染进程的关闭窗口请求
    ipcMain.on('close-window', (event) => {
        win.close();
    });

    ipcMain.handle('download-template', async () => {
        const filePath = join(__dirname, 'public', 'template.xls'); // 获取文件路径
        const {filePath: savePath} = await dialog.showSaveDialog({
            defaultPath: getFileName(), // 默认文件名
            filters: [
                {name: 'Excel Files', extensions: ['xls']}
            ]
        });

        if (savePath) {
            // 这里可以复制文件到用户选择的路径
            const fs = require('fs');
            fs.copyFileSync(filePath, savePath);
            return savePath;
        }
    });
    ipcMain.handle('save-excel', async (event, param) => {
        const params = JSON.parse(param);
        const {headers, data, fileName} = params;

        const workbook = new ExcelJS.Workbook();
        const worksheet = workbook.addWorksheet('Sheet1');
        // 定义边框样式
        const thinBorder = {
            top: {style: 'thin'},
            left: {style: 'thin'},
            bottom: {style: 'thin'},
            right: {style: 'thin'}
        };

        // 定义文本对齐方式
        const leftAlign = { horizontal: 'left' };

        const headerRow = worksheet.addRow(headers.map(item => item.lable));
        headerRow.font = {name: '微软雅黑', size: 10};
        headerRow.alignment = leftAlign; // 设置表头文本居左对齐
        headerRow.eachCell(cell => {
            cell.border = thinBorder
        });

        const keys = headers.map(item => item.prop)
        // 设置列宽
        headers.forEach((item, index) => {
            worksheet.getColumn(index + 1).width = item.width;
        });
        // 添加数据
        data.forEach(row => {
            let obj = {}
            keys.forEach(key => {
                obj[key] = row[key];
                if (obj[key] === undefined) {
                    obj[key] = ""
                }
            });
            const dataRow = worksheet.addRow(Object.values(obj));
            dataRow.font = {name: '微软雅黑', size: 10};
            dataRow.alignment = leftAlign; // 设置表头文本居左对齐
            // 设置数据统计行边框
            dataRow.eachCell(cell => {
                cell.border = thinBorder
            });
        });


        const dataRow2 = worksheet.addRow(['行数：' + data.length, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']);
        dataRow2.font = {name: '微软雅黑', size: 10};
        dataRow2.alignment = leftAlign; // 设置表头文本居左对齐
        // 设置数据统计行边框
        dataRow2.eachCell(cell => {
            cell.border = thinBorder
        });


        // 初始化20行8列的空白单元格
        for (let i = 0; i < 50; i++) {
            const row = worksheet.addRow(new Array(19).fill('')); // 创建8列的空白行
            row.eachCell(cell => {
                cell.border = thinBorder;
            });
        }

        const defaultPath = app.getPath('documents');
        // 弹出路径选择对话框
        const {filePath} = await dialog.showSaveDialog({
            title: '保存 Excel 文件',
            defaultPath: `${defaultPath}/${fileName}`
        });

        if (filePath) {
            await workbook.xlsx.writeFile(filePath); // 直接写入指定路径
            return {success: true, path: filePath};
        }
        return {success: false};
    });
    ipcMain.handle('UserPage', async (event, param) => {
        if (param) {
            param = JSON.parse(param)
        }
        return user.queryData(param);
    });
    ipcMain.handle('HandleInsert', (event, param) => {
        if (param) {
            param = JSON.parse(param)
        }
        return user.insertData(param);
    });
    ipcMain.handle('HandleUpdate', (event, param) => {
        if (param) {
            param = JSON.parse(param)
        }
        return user.updateData(param);
    });
    ipcMain.handle('HandleDelete', async (event, param) => {
        return user.deleteData(param);
    });

    // ipcMain.handle('read-file', (event, filePath) => {
    //     return fs.readFileSync(filePath);
    // });


    // 窗口关闭提示
    // win.on('close', (e) => {
    //     e.preventDefault()
    //     // 窗口关闭提示弹框
    //     win && dialog.showMessageBox(win, {
    //         type: 'info',
    //         title: '退出提示',
    //         message: '是否要退出医师电子化注册信息系统（机构版）？',
    //         buttons: ['Yes', 'No'],
    //         cancelId: 1,
    //     }).then((idx) => {
    //         if(idx.response !== 1) {
    //             app.exit()
    //         }
    //     })
    // })
}


const getFileName = () => {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1;
    const day = now.getDate();
    const hour = now.getHours();
    const minute = now.getMinutes();
    const second = now.getSeconds();
    // 动态文件名
    return `导出文件-${year}-${month}-${day}_${hour}-${minute}-${second}.xlsx`;
}

// electron 会在初始化后准备
app.whenReady().then(() => {
    createWindow()

    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
})
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit()
})